﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace ARCam3D.Imaging.Processing
{
    public class EdgeDetector
    {
        unsafe public VectorImage DetectEdges(GrayscaleImage image)
        {
            int componentsCount = VectorImage.ComponenetsCount;
            int xOffset = VectorImage.XOffset;
            int yOffset = VectorImage.YOffset;

            VectorImage result = new VectorImage(image.Width, image.Height);

            byte v00, v01, v02, v10, v12, v20, v21, v22;

            byte* imageDataPointer = (byte*)image.DataPtr.ToPointer();
            int* resultDataPointer = (int*)result.DataPtr;
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++, resultDataPointer += componentsCount)
                {
                    if (x <= 0 || x >= image.Width - 1 || y <= 0 || y >= image.Height - 1)
                    {
                        resultDataPointer[xOffset] = 0;
                        resultDataPointer[yOffset] = 0;
                        continue;
                    }

                    v00 = image.GetValue(x - 1, y - 1);
                    v01 = image.GetValue(x - 1, y);
                    v02 = image.GetValue(x - 1, y + 1);

                    v10 = image.GetValue(x, y - 1);
                    v12 = image.GetValue(x, y + 1);

                    v20 = image.GetValue(x + 1, y - 1);
                    v21 = image.GetValue(x + 1, y);
                    v22 = image.GetValue(x + 1, y + 1);

                    resultDataPointer[xOffset] = v20 + v22 + 2 * v21 - v00 - v02 - 2 * v01;
                    resultDataPointer[yOffset] = v02 + v22 + 2 * v12 - v00 - v20 - 2 * v10;
                }
            }

            return result;
            //return null;
        }
    }
}
